package com.TripMate.system.controller;

import com.TripMate.system.annotation.AuthCheck;
import com.TripMate.system.common.BaseResponse;
import com.TripMate.system.common.DeleteRequest;
import com.TripMate.system.common.ErrorCode;
import com.TripMate.system.common.ResultUtils;
import com.TripMate.system.constant.UserConstant;
import com.TripMate.system.exception.BusinessException;
import com.TripMate.system.exception.ThrowUtils;
import com.TripMate.system.model.dto.post.PostAddRequest;
import com.TripMate.system.model.dto.post.PostQueryRequest;
import com.TripMate.system.model.dto.post.PostUpdateRequest;
import com.TripMate.system.model.dto.user.*;
import com.TripMate.system.model.entity.Post;
import com.TripMate.system.model.entity.User;
import com.TripMate.system.model.vo.AiHistoryVO;
import com.TripMate.system.model.vo.LoginUserVO;
import com.TripMate.system.model.vo.PostVO;
import com.TripMate.system.model.vo.UserVO;
import com.TripMate.system.service.PostService;
import com.TripMate.system.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 旅行文案接口
 *
 * @author dongyanmian
 */
@RestController
@RequestMapping("/post")
@Slf4j
@Api(tags = "旅行文案接口")
public class PostController {

    @Resource
    private UserService userService;

    @Resource
    private PostService postService;

    // region 增删改查

    /**
     * 创建旅行文案接口
     *
     * @param postAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @ApiOperation("旅行文案接口")
    public BaseResponse<Long> addPost(@RequestBody PostAddRequest postAddRequest, HttpServletRequest request) {
        if (postAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Post post = new Post();
        BeanUtils.copyProperties(postAddRequest, post);
        Long id = userService.getLoginUser(request).getId();
        post.setUserId(id);
        boolean result = postService.save(post);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "创建旅行文案接口失败");
        return ResultUtils.success(post.getId());
    }

    /**
     * 删除旅行文案接口
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @ApiOperation("删除旅行文案接口(管理员可以删除任意用户的旅行文案)")
    public BaseResponse<Boolean> deletePost(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long id = userService.getLoginUser(request).getId();
        Post post = new Post();
        boolean result = postService.removeById(deleteRequest.getId());
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "删除旅行文案接口失败");
        return ResultUtils.success(result);
    }

    /**
     * 更新旅行文案接口
     *
     * @param postUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    @ApiOperation("更新旅行文案接口")
    public BaseResponse<Boolean> updatePost(@RequestBody PostUpdateRequest postUpdateRequest, HttpServletRequest request) {
        if (postUpdateRequest == null || postUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数错误");
        }

        Post post = new Post();
        Long id = userService.getLoginUser(request).getId();

        if (!id.equals(post.getUserId()) || !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限更新旅行文案");
        }

        QueryWrapper<Post> postQueryWrapper = new QueryWrapper<>();
        postQueryWrapper.eq("id", postUpdateRequest.getId());

        Post one = postService.getOne(postQueryWrapper);
        if (one == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "旅行文案不存在");
        }
        if (StringUtils.isBlank(postUpdateRequest.getTitle())) {
            postUpdateRequest.setTitle(one.getTitle());
        }
        if (StringUtils.isBlank(postUpdateRequest.getContent())) {
            postUpdateRequest.setContent(one.getContent());
        }
        if (StringUtils.isBlank(postUpdateRequest.getImage())) {
            postUpdateRequest.setImage(one.getImage());
        }

        BeanUtils.copyProperties(postUpdateRequest, post);
        boolean result = postService.updateById(post);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "更新旅行文案接口失败");
        return ResultUtils.success(result);
    }

    /**
     * 分页获取旅行文案（仅管理员）
     *
     * @param postQueryRequest
     * @return
     */
    @PostMapping("/list/all")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation("分页获取全部的旅行文案（仅管理员）")
    public BaseResponse<Page<PostVO>> listUserByPage(@RequestBody PostQueryRequest postQueryRequest) {
        long current = postQueryRequest.getCurrent() == 0 ? 1 : postQueryRequest.getCurrent();
        long size = postQueryRequest.getPageSize() == 0 ? 10 : postQueryRequest.getPageSize();

        Page<PostVO> pageParam = new Page<>(current, size);
        Page<PostVO> postVOPage = postService.getQueryByAll(pageParam, postQueryRequest);
        if (postVOPage == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "查询失败");
        }
        return ResultUtils.success(postVOPage);
    }

    /**
     * 分页获取自己的旅行文案
     *
     * @param postQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/all/my")
    @ApiOperation("分页获取自己的旅行文案接口")
    public BaseResponse<Page<PostVO>> listPostVOByPage(@RequestBody PostQueryRequest postQueryRequest, HttpServletRequest request) {
        long current = postQueryRequest.getCurrent() == 0 ? 1 : postQueryRequest.getCurrent();
        long size = postQueryRequest.getPageSize() == 0 ? 10 : postQueryRequest.getPageSize();

        Long userId = userService.getLoginUser(request).getId();

        Page<PostVO> pageParam = new Page<>(current, size);
        Page<PostVO> postVOPage = postService.getQueryByMy(pageParam, postQueryRequest, userId);
        if (postVOPage == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "查询失败");
        }
        return ResultUtils.success(postVOPage);
    }

    // endregion
}
